package cn.ito.zjgsu.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;

import cn.ito.zjgsu.constant.StatusCode;
import cn.ito.zjgsu.domain.View;
import cn.ito.zjgsu.domain.ViewExample;
import cn.ito.zjgsu.mapping.ViewMapper;
import cn.ito.zjgsu.service.ViewService;

//传view的时候按number升序排列
@Service
@Transactional
public class ViewServiceImpl implements ViewService {

	@Resource
	private ViewMapper viewMapper;

	// C
	// R
	public List<View> queryViewsByExample(ViewExample viewExample) {
		List<View> views = viewMapper.selectByExample(viewExample);
		return views;
	}

	// U
	@Override 
	public String saveState(List<View> views) {
		String status = StatusCode.FAILURE_STATUS;
		try {
			if (null == views || views.isEmpty()) {
			} else {
				// 1查询所有视图记录
				ViewExample viewExample = new ViewExample();
				viewExample.or().andModelNameEqualTo(views.get(0).getModelName());
				List<View> vws = queryViewsByExample(viewExample);
				viewMapper.deleteByExample(viewExample);
				
				//views 传过来的可能有残缺，带着新顺序      vws 数据库里的全的 ，旧的
				
				//取差
				List<View> dlist = new ArrayList<View>();
				for(View v: vws){
					for(int i = 0 ; i < views.size() ; i++){
						View v1 = views.get(i);
						if(v1.getFieldname().equals(v.getFieldname())){
							break;
						}
						else if(i == views.size() -1){
							v.setNumber(-1);
							v.setChecked(false);
							dlist.add(v);
						}
					}
				}
				
				views.addAll(dlist);
							
				// 5批量插入
				viewMapper.insertList(views);
				status = StatusCode.SUCCESS_STATUS;
			}
		} catch (Exception e) {
			e.printStackTrace();
			status = StatusCode.FAILURE_STATUS;
		}
		return status;
	}

	@Override
	public List<String> queryAllModelName() {
		List<String> modelNames = viewMapper.queryAllModelName();
		return modelNames;
	}

	

	// D

}
